package com.km.wskj.itmonitor.pager.monitor.database.mysql;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.Cpu;
import com.km.wskj.itmonitor.model.DBDetail;
import com.km.wskj.itmonitor.model.DataBase;
import com.km.wskj.itmonitor.model.FuncItem;
import com.km.wskj.itmonitor.model.Memory;
import com.km.wskj.itmonitor.model.MySQLSize;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.AlarmListNoSpinnerActivity;
import com.km.wskj.itmonitor.pager.monitor.database.DBConfigActivity;
import com.km.wskj.itmonitor.pager.monitor.server.ServerListActivity;
import com.km.wskj.itmonitor.utils.DynamicChartUtils;
import com.km.wskj.itmonitor.utils.FloatUtils;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class
MySQLDetailActivity extends LActivity implements OnChartValueSelectedListener {
    private static final String TAG = "MySQLDetailActivity";

    //data
    private String ip;
    private String id;
    private DataBase mDataBase;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // 在此处添加执行的代码
            initData();
            handler.postDelayed(this, 5000);// 5000ms后执行this，即runable
        }
    };


    //ui
    @BindView(R.id.tool_bar_back)
    ImageView mBack;
    @BindView(R.id.tool_bar_title)
    TextView mTitle;
    @BindView(R.id.tool_bar_right_text)
    TextView mRightText;
    @BindView(R.id.tv_mysql_instance_name)
    TextView mInstance;
    @BindView(R.id.tv_mysql_version)
    TextView mVersion;


    //chart
    @BindView(R.id.chart_db_cpu)
    LineChart mCpuChart;//cpu占用率
    @BindView(R.id.chart_db_physics)
    LineChart mPhyChart;//物理内存使用率
    @BindView(R.id.mysql_detail_barchart)
    BarChart mBarChart;//柱状图


    @BindView(R.id.tv_mysql_max_connections)
    TextView mMaxConn;//设置连接数
    @BindView(R.id.tv_mysql_max_used_connections)
    TextView mUsed;//当前连接数
    @BindView(R.id.tv_mysql_threads_running)
    TextView mThreadsRunning;//活跃线程数
    @BindView(R.id.tv_mysql_innodb_lock_waits)
    TextView mInnodb;//查询锁等待
    @BindView(R.id.tv_mysql_cpu)
    TextView mCpu;//cpu
    @BindView(R.id.tv_mysql_physical_memory)
    TextView mPhy;//物理内存

    @BindView(R.id.mysql_container_gridview)
    LinearLayout container_gridview;

    //data
    List<FuncItem> funcItems = new ArrayList<>();
    private MyGridView gridView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mysql_detail);
        ButterKnife.bind(this);

        if (getIntent().hasExtra("ip"))
            ip = getIntent().getStringExtra("ip");
        if (getIntent().hasExtra("id"))
            id = getIntent().getStringExtra("id");
        mDataBase = (DataBase) getIntent().getSerializableExtra("data");

        //初始化线性图
        DynamicChartUtils.initChart(mCpuChart, Color.parseColor("#ffffff"));
        DynamicChartUtils.initChart(mPhyChart, Color.parseColor("#ffffff"));

        initFuncItems();
        initData();
        initMySqlSize();

        container_gridview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                container_gridview.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                createGridView();
            }
        });

        handler.postDelayed(runnable, 5000);

    }

    //表大小统计图
    private void initMySqlSize() {
        //mysql表大小请求方法
        pdc.mysqlSize(HTTP_TASK_TAG, id, new ZxlGenericsCallback<List<MySQLSize>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(List<MySQLSize> mys, int i) {
                initBarChart(mys);
            }
        });
    }


    private void initData() {
        mBack.setVisibility(View.VISIBLE);
        mRightText.setVisibility(View.VISIBLE);
        mTitle.setText(mDataBase.databaseName + "数据库");
        mInstance.setText(mDataBase.databaseName + "\nACTIVE");
        mVersion.setText(mDataBase.databaseVersion + "");
        mRightText.setText("报告");

        initCpuPhy();
        initDbInfo();


    }


    /**
     * 柱状图
     */
    private void initBarChart(final List<MySQLSize> mySQLSizes) {
        mBarChart.getDescription().setEnabled(false);
//        mChart.setDrawBorders(true);
        // scaling can now only be done on x- and y-axis separately
        mBarChart.setPinchZoom(false);
        mBarChart.setDrawBarShadow(false);
        mBarChart.setDrawGridBackground(false);


        Legend l = mBarChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(true);
        l.setYOffset(0f);
        l.setXOffset(10f);
        l.setYEntrySpace(0f);
        l.setTextSize(8f);

        XAxis xAxis = mBarChart.getXAxis();
        xAxis.setGranularity(1f);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setCenterAxisLabels(true);
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(false);
        xAxis.setLabelRotationAngle(-15f);
        // x轴数据
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                // x轴数据
                List<String> data = new ArrayList<>();

                for (int i = 0; i < mySQLSizes.size(); i++) {
                    data.add(mySQLSizes.get(i).table_name);
                }

                String str = null;
                if ((int) value >= 0 && (int) value < data.size())
                    str = data.get((int) value);

                return str == null ? value + "" : str;
            }
        });

        YAxis leftAxis = mBarChart.getAxisLeft();
        leftAxis.setValueFormatter(new LargeValueFormatter());
        leftAxis.setDrawGridLines(true);
        leftAxis.setSpaceTop(35f);
        leftAxis.enableGridDashedLine(10f, 10f, 0f); //设置网格线为虚线效果
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        leftAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return FloatUtils.doubleFloat(value) + "";
            }
        });

        mBarChart.getAxisRight().setEnabled(false);


        float groupSpace = 0.08f;
        float barSpace = 0.03f; // x4 DataSet
        // (0.2 + 0.03) * 4 + 0.08 = 1.00 -> interval per "group"


        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        ArrayList<BarEntry> yVals2 = new ArrayList<BarEntry>();

        for (int i = 0; i < mySQLSizes.size(); i++) {

            String data_size = mySQLSizes.get(i).data_size;
            String index_size = mySQLSizes.get(i).index_size;

            //数据文件大小
            yVals1.add(new BarEntry(i, Float.parseFloat(data_size)));
            //索引文件大小
            yVals2.add(new BarEntry(i, Float.parseFloat(index_size)));
        }

        BarDataSet set1, set2;

        if (mBarChart.getData() != null && mBarChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mBarChart.getData().getDataSetByIndex(0);
            set2 = (BarDataSet) mBarChart.getData().getDataSetByIndex(1);

            set1.setValues(yVals1);
            set2.setValues(yVals2);

            mBarChart.getData().notifyDataChanged();
            mBarChart.notifyDataSetChanged();

        } else {
            // create 4 DataSets
            set1 = new BarDataSet(yVals1, "数据文件大小");
            set1.setColor(Color.rgb(104, 241, 175));
            set2 = new BarDataSet(yVals2, "索引文件大小");
            set2.setColor(Color.rgb(164, 228, 251));

            BarData data = new BarData(set1, set2);

//            data.setValueFormatter(new LargeValueFormatter());

            mBarChart.setData(data);
        }
        // specify the width each bar should have
        mBarChart.getBarData().setBarWidth(0.43f);
        // restrict the x-axis range
        mBarChart.getXAxis().setAxisMinimum(0);
        // barData.getGroupWith(...) is a helper that calculates the width each group needs based on the provided parameters
        mBarChart.getXAxis().setAxisMaximum(5f);
        mBarChart.groupBars(0f, groupSpace, barSpace);
        mBarChart.invalidate();
    }

    /**
     * 数据库信息
     */
    private void initDbInfo() {
        pdc.databaseDetail(HTTP_TASK_TAG, id, new ZxlGenericsCallback<DBDetail>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("加载错误");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(DBDetail dbd, int i) {
                mMaxConn.setText(dbd.max_connections + "");
                mThreadsRunning.setText(dbd.threads_running + "");
                mUsed.setText(dbd.max_used_connections + "");
                mInnodb.setText(dbd.innodb_lock_waits + "");
            }
        });

    }

    /**
     * 物理内存使用率和cpu使用率
     */

    private void initCpuPhy() {
        pdc.cpu(HTTP_TASK_TAG, ip, new ZxlGenericsCallback<Cpu>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("加载错误");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(Cpu cpu, int i) {
                if (cpu.total != null) {
                    mCpu.setText(cpu.total + "%");
                    DynamicChartUtils.addEntry(mCpuChart, FloatUtils.doubleFloat(Float.parseFloat(cpu.total)));
                }
            }
        });


        pdc.memory(HTTP_TASK_TAG, ip, new ZxlGenericsCallback<Memory>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("加载错误");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(Memory memory, int i) {
                float v = Float.parseFloat(memory.usedPhysicsMem) / Float.parseFloat(memory.physicsMem);
                float v1 = FloatUtils.doubleFloat(v * 100);
                mPhy.setText(v1 + "%");
                DynamicChartUtils.addEntry(mPhyChart, v1);
            }
        });
    }

    //历史性能
    @OnClick(R.id.tool_bar_right_text)
    public void menu() {

    }

    //返回点击事件
    @OnClick(R.id.tool_bar_back)
    public void back() {
        finish();
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(runnable);
        super.onDestroy();
    }


    private void initFuncItems() {
        String s[] = getResources().getStringArray(R.array.mysql_func_title_array);
        String index[] = getResources().getStringArray(R.array.mysql_func_index);
        int r[] = {R.mipmap.lsxn_blue
                , R.mipmap.qt_blue
                , R.mipmap.db_blue
                , R.mipmap.config_blue
                , R.mipmap.alarm_blue
                , R.mipmap.jxsm_blue
                , R.mipmap.aqld_blue
                , R.mipmap.ccxx_blue
                , R.mipmap.gl_blue
                , R.mipmap.lsxn_blue
        };

        funcItems.clear();


        for (int i = 0; i < s.length && i < r.length; i++) {
            FuncItem fi = new FuncItem();
            fi.name = s[i];
            fi.resId = r[i];
            fi.index = index[i];
            funcItems.add(fi);
        }
    }


    private void createGridView() {

        gridView = new MyGridView(context, new MyGridView.MyGridViewAdapter() {
            @Override
            public int rowspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int leftpadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int toppadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colCount(MyGridView myGridView) {
                return 4;
            }

            @Override
            public int rowHeight(MyGridView myGridView) {
                return container_gridview.getHeight() / 3;
            }

            @Override
            public int viewWidth(MyGridView myGridView) {
                return container_gridview.getWidth();
            }

            @Override
            public int count(MyGridView myGridView) {
                return funcItems.size();
            }

            @Override
            public View cell(int i, MyGridView myGridView) {
                View view = getLayoutInflater().inflate(R.layout.monitor_item_func, null);
                ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_pic);
                TextView tv_name = (TextView) view.findViewById(R.id.tv_name);

                FuncItem fi = funcItems.get(i);
                iv_pic.setImageResource(fi.resId);
                tv_name.setText(fi.name);
                return view;
            }

            @Override
            public View title(int i, MyGridView myGridView) {
                return null;
            }

            @Override
            public int titleOffsetY(MyGridView myGridView) {
                return 0;
            }

            @Override
            public boolean needGridLine(MyGridView myGridView) {
                return true;
            }
        });


        gridView.setListener(new MyGridView.MyGridViewListener() {
            @Override
            public void onCellTouchDown(int i) {

            }

            @Override
            public void onCellTouchUp(int i) {

            }

            @Override
            public void onCellLongPress(int i) {

            }

            @Override
            public void onCellClick(int i) {
                switch (i) {
                    //性能
                    case 0: {
                        Intent t = new Intent(context, MySQLPerformActivity.class);
                        t.putExtra("id", id);
                        startActivity(t);
                    }
                    break;
                    //启停
                    case 1: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //备份
                    case 2: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //配置
                    case 3: {
                        Intent t = new Intent(context, DBConfigActivity.class);
                        t.putExtra("id", id);
                        startActivity(t);
                    }
                    break;
                    //报警
                    case 4: {
                        Intent t = new Intent(context, AlarmListNoSpinnerActivity.class);
                        t.putExtra("id", id);
                        startActivity(t);
                    }
                    break;
                    //基线扫描
                    case 5: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //安全漏洞
                    case 6: {
                        normalToasty("暂未开放功能");

                    }
                    break;
                    //服务器
                    case 7: {
                        openIntent(ServerListActivity.class, true);
                    }
                    break;
                    //关联
                    case 8: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //报告
                    case 9: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                }
            }
        });
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        container_gridview.addView(gridView.getView(), p);
    }


    //柱状图
    @Override
    public void onValueSelected(Entry e, Highlight h) {
        Log.i(TAG, "Selected: " + e.toString() + ", dataSet: " + h.getDataSetIndex());
    }

    @Override
    public void onNothingSelected() {
        Log.i(TAG, "Nothing selected.");
    }


}
